package com.lw.chat.view.chat;

import cn.hutool.core.util.StrUtil;
import de.saxsys.mvvmfx.FxmlView;
import de.saxsys.mvvmfx.InjectViewModel;
import javafx.beans.binding.Bindings;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Pos;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.shape.Polygon;

import java.net.URL;
import java.util.ResourceBundle;

/**
 * @description:
 * @className: ChatController
 * @author: liwen
 * @date: 2020/12/13 13:34
 */
public class MessageBoxView implements FxmlView<MessageBoxViewModel>, Initializable {

    @FXML
    private HBox rootPane;
    @FXML
    private ImageView avatarImageView;
    @FXML
    private Label userNameLabel;
    @FXML
    private Label msgLabel;
    @FXML
    private ImageView msgImageView;

    @FXML
    private Polygon polygon;

    @FXML
    private VBox msgPane;

    @InjectViewModel
    private MessageBoxViewModel messageBoxViewModel;

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {

        messageBoxViewModel.subscribe("msgStyle",(key, payload) -> {
            if (  messageBoxViewModel.otherSideProperty().getValue()) {
                rootPane.setAlignment(Pos.TOP_LEFT);
                polygon.getStyleClass().add("msg-arrow");
                msgPane.getStyleClass().add("chat-bubble");
            }else {

                rootPane.setAlignment(Pos.TOP_RIGHT);
                polygon.getStyleClass().add("msg-arrow-me");
                msgPane.getStyleClass().add("chat-bubble-me");
            }
        });
        avatarImageView.imageProperty().bind(Bindings.createObjectBinding(
                () ->StrUtil.isEmpty(messageBoxViewModel.avatarUriProperty().getValue()) ?null: new Image(messageBoxViewModel.avatarUriProperty().getValue()), messageBoxViewModel.avatarUriProperty())
        );
        msgImageView.imageProperty().bind(Bindings.createObjectBinding(
                () -> StrUtil.isEmpty(messageBoxViewModel.msgImageUriProperty().getValue()) ?null:new Image(messageBoxViewModel.msgImageUriProperty().getValue()), messageBoxViewModel.msgImageUriProperty())
        );
        userNameLabel.textProperty().bind(messageBoxViewModel.userNameProperty());
        msgLabel.textProperty().bind(messageBoxViewModel.messageProperty());

        userNameLabel.visibleProperty().bind(messageBoxViewModel.userNameProperty().isNotEmpty());
        userNameLabel.managedProperty().bind(userNameLabel.visibleProperty());
        msgImageView.visibleProperty().bind(messageBoxViewModel.msgImageUriProperty().isNotNull());
        msgImageView.managedProperty().bind(msgImageView.visibleProperty());

    }


}
